package com.station.xml;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import java.util.List;


/**
 * 标准返回xml格式SAX解析器，标准格式见 XmlResult
 *@author hehc
 */
public class XmlObjectParserHandler extends BaseHandler{

	protected String currentEleName="";
	protected String preEleName="";
	
	private StringBuilder sb;
	private boolean flag = false;
	
	//以下为data标签下的解析对象结果
	private List<Object> objs;
	private Object obj;
	//以下为detail标签下的解析对象结果（detail下有子对象）
	private List<Object> childs;
	private Object child;
	
	//是否刚刚执行完endElement
	private boolean endElement = false;
	//是否刚刚执行完startElement
	private boolean startElement = false;
    
	public XmlObjectParserHandler() {
	}
	public XmlObjectParserHandler(String TAG){
		Data.TAG_DETAIL=TAG;
	}
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		String str=new String(ch,start,length);  
		if(!flag) {    
            return;    
        }
		sb.append(str);  
	}
	
	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		if(result == null){
			throw new SAXException("Please set the value of XmlResult first!");
		}
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		flag = false; 
		
		if(XmlResult.TAG_RETURNCODE.equals(currentEleName)) {
        	result.setReturnCode(sb.toString());
        }
        else if(XmlResult.TAG_RETURNSTR.equals(currentEleName)) {
        	result.setReturnStr(sb.toString());
        }
        else if (XmlResult.TAG_COUNT.equals(currentEleName)){
			try{
				result.setCount(Long.parseLong(sb.toString()));
			}
			catch(NumberFormatException e){
			}
		}else if (XmlResult.TAG_TOTALCOUNT.equals(currentEleName)){
			try{
				result.setTotalCount(Long.parseLong(sb.toString()));
			}
			catch(NumberFormatException e){
			}
		}else if(XmlResult.TAG_DATA.equals(localName)){
			//empty
		}else if(Data.TAG_DETAIL.equals(localName)){
			if(obj instanceof SubObjFieldSupport){
				((SubObjFieldSupport)obj).childsToFields();
			}
			if(obj instanceof KVSupport){
				((KVSupport)obj).kvInject();
			}
			objs.add(obj);
			obj = null;
		}else{//对象属性字段值，注入对象
			if(child != null){//有子对象先注入完
				XmlObjectHelper.parserObject(this.child, sb.toString(), currentEleName);
			}else{
				XmlObjectHelper.parserObject(this.obj, sb.toString(), currentEleName);
			}
		}
		
		if(!startElement){//之前没有开始Tag，说明当前是父标签的结束
			if(child != null){
				if(child instanceof KVSupport){
					((KVSupport)child).kvInject();
				}
				childs.add(child);
				child = null;
			}
		}
		
		this.preEleName = this.currentEleName.equals("")?localName:currentEleName;
		this.currentEleName = "";
		endElement = true;
		startElement=false;
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		sb = new StringBuilder();
		flag = true; 
		try {
			if(XmlResult.TAG_DATA.equals(localName)){
				objs=result.getData().getDetails();
			}else if (Data.TAG_DETAIL.equals(localName)) {
				obj = result.getData().newDetail();
			}else if(!XmlResult.TAG_ROOT.equals(localName)){
				//判断是否为上个Tag的子对象
				if(!endElement){//之前没有结束Tag，说明当前是上个Tag的子元素
					if(!preEleName.equals("")
							&& !preEleName.equals(XmlResult.TAG_ROOT)//只要上个标签不是确定的内置标签，就说明需要创建对象，为detail下的子对象
							&& !preEleName.equals(XmlResult.TAG_DATA)
							&& !preEleName.equals(Data.TAG_DETAIL)
							){
						//创建子对象
						child = XmlObjectHelper.initFieldClazzObject(obj, preEleName);
						if(childs == null){
							if(obj instanceof SubObjFieldSupport){
								childs = ((SubObjFieldSupport)obj).getChilds();
							}else{
								throw new SAXException("对象未继承 SubObjFieldSupport，不支持子对象解析");
							}
						}
					}else{
						child = null;
					}
				}
			}
			
			this.currentEleName = localName;
			this.preEleName = this.currentEleName;
			endElement = false;
			startElement = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
